﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.IO.Compression;

namespace OBNEPGGrabber
{
    static class Unzipper
    {
        private static string m_strZippedFile = null;
        private static string m_strUnzippedFile = null;
        private static DirectoryInfo m_dirInfo = null;
        private static IStatusUpdate m_IUpdate = null;

        public static void Unzip(string strZippedFile, DirectoryInfo dirInfo, string strUnzippedFile, bool bDelete, IStatusUpdate IStatusUpdate)
        {
            m_strUnzippedFile = strUnzippedFile;
            m_strZippedFile = strZippedFile;
            m_dirInfo = dirInfo;
            m_IUpdate = IStatusUpdate;
            UnzipFile();
            if (bDelete)
            {
                try
                {
                    File.Delete(m_dirInfo.FullName + "\\" + m_strZippedFile);
                }
                catch ( Exception )
                {
                    m_IUpdate.UpdateStatus("Error deleting zipfile " + m_strZippedFile, false);
                }
            }
        }

        private static void UnzipFile()
        {
            try
            {
                // Bytes array in which we're going to store the actual file to be decompressed

                byte[] bufferWrite;
                
                FileStream fsSource;
                FileStream fsDest;

                GZipStream gzDecompressed;

                fsSource = new FileStream(m_dirInfo.FullName + "\\" + m_strZippedFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                gzDecompressed = new GZipStream(fsSource, CompressionMode.Decompress, true);

                bufferWrite = new byte[4];
                fsSource.Position = (int)fsSource.Length - 4;
                fsSource.Read(bufferWrite, 0, 4);
                fsSource.Position = 0;
                int bufferLength = BitConverter.ToInt32(bufferWrite, 0);
                byte[] buffer = new byte[bufferLength + 100];
                int readOffset = 0;
                int totalBytes = 0;

                while (true)
                {
                    int bytesRead = gzDecompressed.Read(buffer, readOffset, 100);

                    if (bytesRead == 0)
                        break;
                    readOffset += bytesRead;
                    totalBytes += bytesRead;
                }
                
                fsDest = new FileStream(m_dirInfo.FullName + "\\" + m_strUnzippedFile, FileMode.Create);

                fsDest.Write(buffer, 0, totalBytes);
                fsSource.Close();
                gzDecompressed.Close();
                fsDest.Close();
            }
            catch (Exception)
            {
                m_IUpdate.UpdateStatus("Error unzipping channel list file" + m_strZippedFile, true);
            }
        }
    }
}
